unit uRandom;
interface
uses uFloat;
{$INCLUDE options.inc}
{$INCLUDE proto.inc}

procedure SetRandomSeed(Seed: shortstring);
function GetRandom: hwFloat; overload;
function GetRandom(m: LongWord): LongWord; overload;
function  rndSign(num: hwFloat): hwFloat;
{$IFDEF DEBUGFILE}
procedure DumpBuffer;
{$ENDIF}

implementation
{$IFDEF DEBUGFILE}
uses uMisc;
{$ENDIF}

var cirbuf: array[0..63] of Longword;
	n: byte = 54;
	
function GetNext: Longword
begin
	n:= (n + 1) and $3F;
	cirbuf[n]:=
           (cirbuf[(n + 40) and $3F] +           {n - 24 mod 64}
            cirbuf[(n +  9) and $3F])            {n - 55 mod 64}
            and $7FFFFFFF;                       {mod 2^31}
    
    GetNext := cirbuf[n]
end;

procedure SetRandomSeed(Seed: shortstring);
var i: Longword;
begin
	n:= 54;
	
	if Length(Seed) > 54 then Seed:= copy(Seed, 1, 54); // not 55 to ensure we have odd numbers in cirbuf
	
	for i:= 0 to Pred(Length(Seed)) do
		cirbuf[i]:= byte(Seed[i + 1]);
	
	for i:= Length(Seed) to 54 do
		cirbuf[i]:= $A98765 + (cNetProtoVersion * 2); // odd number
		
	for i:= 0 to 1023 do GetNext
end;

function GetRandom: hwFloat;
begin
	GetNext;
	GetRandom.isNegative:= false;
	GetRandom.QWordValue:= GetNext
end;

function GetRandom(m: LongWord): LongWord;
begin
	GetNext;
	GetRandom := GetNext mod m
end;

function rndSign(num: hwFloat): hwFloat;
begin
	num.isNegative := odd(GetNext);
	rndSign := num;
end;

{$IFDEF DEBUFILE}
procedure DumpBuffer;
var i: LongInt;
begin
	for i := 0 to 63 do
		AddFileLog('[' + inttostr(i) + '] = ' + inttostr(cirbuf[i]));
end;
{$ENDIF}

end.
